<template>
  <div>
    <a-input
      :placeholder="l('InXSearchPlaceHolder', l('PermissionDisplayName'))"
      @change="onSearch"
      size="default"
    >
      <template #addonAfter>
        <reload-outlined @click.prevent="reload()" />
      </template>
    </a-input>
    <p></p>
    <a-tree
      v-if="treeData.length"
      checkable
      selectable
      defaultExpandAll
      v-model:checkedKeys="selectedPermissionVal"
      @check="onCheck"
      :tree-data="treeData"
    />
  </div>
</template>

<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import { PermissionServiceProxy } from '/@/shared/service-proxies';
  import { arrayService } from '/@/shared/utils';
  import { defineComponent } from 'vue';
  import { FlatPermissionWithLevelDto } from '/@/shared/service-proxies';
  import { ReloadOutlined } from '@ant-design/icons-vue';

  export default defineComponent({
    name: 'search-role-tree',
    components: {
      ReloadOutlined,
    },
    mixins: [AppComponentBase],

    props: {
      multiple: Boolean,
      dropDownStyle: Object,
      selectedPermission: Array<any>(),
    },
    data() {
      return {
        permissionService: new PermissionServiceProxy(),
        permissions: new Array<FlatPermissionWithLevelDto>(),
        treeData: new Array<any>(),
        treeDataOrgin: new Array<any>(),
        selectedPermissionVal: new Array<any>(),
        selectedKeys: [],
        filterText: '',
        // 模糊查询
        dataList: [],
        selectedItem: [],
      };
    },
    mounted() {
      this.selectedPermissionVal = this.selectedPermission;
      this.permissionService.getAllPermissions().then((result) => {
        this.permissions = result.items ?? [];
        this.permissions.map((item: any) => {
          item.value = item.name;
        });
        this.arrToTreeNode();
      });
    },
    methods: {
      getSelected(treeData) {
        treeData.map((item) => {
          console.log(this.selectedPermission);
          if (this.selectedPermission.indexOf(item.name) > -1 && item.children.length) {
            item.children.map((ele) => {
              if (
                this.selectedPermission.indexOf(ele.name) > -1 &&
                this.selectedPermission.indexOf(item.name) > -1
              ) {
                this.selectedPermissionVal.splice(this.selectedPermission.indexOf(item.name), 1);
              }
            });
          }
          this.getSelected(item.children);
        });
      },
      arrToTreeNode() {
        this.treeData = arrayService.arrToTreeNode(this.permissions, {
          idMapName: 'name',
          parentIdMapName: 'parentName',
          titleMapName: 'displayName',
        });

        // 延时设置子父节点checkbox关联状态，否则有父节点选中则全部选中了
        setTimeout(() => {
          this.loading = false;
        }, 300);
        this.permissions.map((item: any) => {
          this.dataList.push({
            key: item.name,
            title: item.displayName,
          } as never);
        });
        this.getSelected(this.treeData);
        this.selectedItem = this.selectedPermissionVal;
        this.getParentId(this.selectedPermissionVal);
        this.$emit('selectedPermissionChange', this.selectedItem);
        this.treeDataOrgin = [...this.treeData];
      },
      getParentId(val) {
        if (val && val.length) {
          val.map((ele) => {
            this.permissions.map((item) => {
              if (item.name === ele) {
                if (item.parentName && !this.selectedItem.indexOf(item.parentName) > -1) {
                  let temp = [item.parentName];
                  this.selectedItem = [...this.selectedItem, ...temp];
                }
              }
            });
          });
        }
      },
      /**
       * 选中
       */
      onCheck(val) {
        this.selectedItem = val;
        // this.getParentId(val);
        this.selectedPermissionVal = val;

        this.$emit('selectedPermissionChange', val);
      },
      /**
       * 格式化数据 模糊匹配
       */
      getParentKey(key, tree) {
        let parentKey;
        for (let i = 0; i < tree.length; i++) {
          const node = tree[i];
          if (node.children) {
            if (node.children.some((item) => item.title === key)) {
              parentKey = node.title;
            } else if (this.getParentKey(key, node.children)) {
              parentKey = this.getParentKey(key, node.children);
            }
          }
        }
        return parentKey;
      },
      /**
       * 搜索
       */
      onSearch(e) {
        const value = e.target.value;
        this.treeData = this.rebuildData(value, this.treeDataOrgin);
      },
      rebuildData(value, arr) {
        let newarr: any[] = [];
        arr.forEach((element) => {
          if (element.title.indexOf(value) > -1) {
            newarr.push(element);
          } else {
            if (element.children && element.children.length > 0) {
              const ab = this.rebuildData(value, element.children);
              const obj = {
                ...element,
                children: ab,
              };
              if (ab && ab.length > 0) {
                newarr.push(obj);
              }
            }
          }
        });
        return newarr;
      },
      /**
       * 刷新
       */
      reload() {
        this.treeData = this.treeDataOrgin;
      },
    },
  });
</script>

<style scoped></style>
